package cn.edu.dgut.utils;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * httpClientTool为封装httpClient的发送post请求的工具类
 *
 * 其中的主要方法为String getPostInfo(String url, List<BasicNameValuePair> paramList, HttpServletResponse response)
 * 参数为url,list,response
 * 返回一个json字符串
 */

public class httpClientTool {
    public String getPostInfo(String url, List<BasicNameValuePair> paramList, HttpServletResponse response){

        String resultString = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse resp = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 模拟表单
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
            httpPost.setEntity(entity);

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            // 执行http请求
            resp = httpClient.execute(httpPost);
            if(resp.getEntity()!= null) {
                resultString = EntityUtils.toString(resp.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                resp.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }

}
